import { UploadOutlined } from '@ant-design/icons';
import { Button, message, Upload } from 'antd';
import $http from '@/services/http.service.v2';
import $helper from '@/services/helper.service';

export default function RoleUploader({onFinish}) {
  const props = {
    showUploadList: false,
    name: 'file',
    customRequest: function({ file, onSuccess, onError, onProgress }) {
      const formData = new FormData();
      formData.append('file', file);
      const loadingKey = $helper.uuid()
      message.loading({ content: '正在上传...', key: loadingKey })
      $http.uploadRoleJson(formData).subscribe(res => {
        message.destroy(loadingKey)
        if (!res.status) {
          onError(new Error(res.message))
          message.error(`Upload failed! message: ${res.message}`)
          return
        }
        onSuccess(res.data);
        message.success('Upload successful!')
        onFinish && onFinish()
      })
      // try {
      //   // 通过 axios 发送 POST 请求进行上传
      //   const response = await axios.post('/upload', formData, {
      //     headers: {
      //       'Content-Type': 'multipart/form-data',
      //     },
      //     onUploadProgress: (progressEvent) => {
      //       // 计算上传进度并触发 onProgress 回调
      //       const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
      //       onProgress({ percent });
      //     },
      //   });
  
      //   // 上传成功后调用 onSuccess
      //   onSuccess(response.data);
      //   message.success('Upload successful!');
      // } catch (err) {
      //   // 上传失败后调用 onError
      //   onError(err);
      //   message.error('Upload failed!');
      // }
    }
  }
  return (
    <Upload {...props}>
      <Button type="primary" icon={<UploadOutlined />}>导入</Button>
    </Upload>
  )
}